from rest_framework import serializers

from myapp.models import User
from home.models import UserProfile, TieziModel, TagModel, LianjieModel


# 用户
class UserSer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ['id', 'username', 'u_name', 'avatar']


# 个人中心
class UserProfileSer(serializers.ModelSerializer):
    # 关联 UserSer 来获取用户信息
    u_user = UserSer(read_only=True)

    class Meta:
        model = UserProfile
        fields = '__all__'


# 商品连接
class LianjieSer(serializers.ModelSerializer):
    class Meta:
        model = LianjieModel
        fields = '__all__'


# 分类
class TagSer(serializers.ModelSerializer):
    class Meta:
        model = TagModel
        fields = '__all__'


# 帖子
from rest_framework import serializers
# 假设 UserSer 是你自定义的用户序列化器，这里导入它

class TieziSer(serializers.ModelSerializer):
    new_tag = serializers.SerializerMethodField(read_only=True)
    new_lian = serializers.SerializerMethodField(read_only=True)
    # 关联 UserSer 来获取用户信息
    t_user = UserSer(read_only=True)

    def get_new_tag(self, obj):
        # 检查 fen_tag 是否为空
        if obj.fen_tag:
            return obj.fen_tag.t_name
        return None

    def get_new_lian(self, obj):
        # 检查 lianjie 是否为空
        if obj.lianjie:
            return obj.lianjie.l_name
        return None

    class Meta:
        model = TieziModel
        fields = '__all__'


# 帖子添加
from rest_framework import serializers
from home.models import TieziModel
from myapp.models import User
from rest_framework import serializers

class CreateTieziSerializer(serializers.ModelSerializer):
    class Meta:
        model = TieziModel
        fields = ['t_title', 't_content', 't_img', 'fen_tag', 'lianjie']
        extra_kwargs = {
            'fen_tag': {'required': True},
            't_title': {'required': True}
        }



from rest_framework import serializers
from .models import TieziModel

class TieziSerializer(serializers.ModelSerializer):
    class Meta:
        model = TieziModel
        fields = '__all__'
